#include "GameMath.h"
#include "EnemyManager.h"
#include "PlayerManager.h"
#include "../data/GameInfo.h"
#include "../data/Creator.h"
#include "RenderShape.h"

EnemyManager::EnemyManager()
{
}

void EnemyManager::OnUpdate(double delta)
{
    auto &enemies = GameInfo::Instance().enemies;
    enemies.erase(std::remove_if(enemies.begin(), enemies.end(),
                                 [](std::shared_ptr<Character> &enemy) { return enemy->CanRemove(); }), enemies.end());
    for (auto &enemy: enemies) {
        AiAction(enemy);
        enemy->OnUpdate(delta);
    }
}

void EnemyManager::OnRender()

{
    auto &enemies = GameInfo::Instance().enemies;
    for (auto &enemy: enemies) {
        enemy->OnRender();
        RenderShape::RendererEnemyHp(GAME_RENDERER, enemy->position, enemy->GetShape(), enemy->hp, enemy->maxHp);
    }
}

void EnemyManager::AddEnemy(const std::shared_ptr<Character>& enemy)
{
    enemy->id = 1;
    enemy->viewRange = 500;
    for (int i = Facing::Down; i < Facing::SIZE; i++) {
        enemy->animAttack[i].onFinished = [enemy] {
            std::vector<std::shared_ptr<Character>> play = {PlayerManager::Instance().GetPlayer()};
            enemy->OnAttack(play);
        };
    }
    GameInfo::Instance().enemies.emplace_back(enemy);
}

void EnemyManager::AiAction(const std::shared_ptr<Character>& enemy)
{
    if (AiCanAttack(enemy)) {
        enemy->Attack();
        return;
    }
    auto playerPosition = PlayerManager::Instance().GetPosition();
    enemy->direction = (playerPosition - enemy->position);
    if (enemy->direction.Length() > enemy->viewRange) enemy->direction = {0, 0};
}

bool EnemyManager::AiCanAttack(const std::shared_ptr<Character>& enemy)
{
    auto player = PlayerManager::Instance().GetPlayer();
    auto attackPair = enemy->GetAttackPosition();
    if (GameMath::CollisionDetection(attackPair.first, attackPair.second,
                                     player->position, player->GetShape())) {
        return true;
    }
    return false;
}